<template>
  <div class="pager">
        <el-form :model="form" ref="form" label-width="200px" v-loading="formLoading" :rules="rules">
        <el-form-item label="选择班级：" prop="classId" clearable required>
        <el-select v-model="form.classId" placeholder="请选择" @click="getClass">
          <el-option v-for="item in classList" :key="item.id" :label="item.className" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="学生名单：" required>
        <el-upload
          class="upload-demo"
          action="http://175.24.33.88:8000/api/admin/excel/import_excel_for_student"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          ref='upload'
          :file-list='fList'
          multiple
          :auto-upload="true"
          :http-request="cfileUpload"
          :with-credentials="true"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传.xlx/.xlsx文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>



 </el-form>
  </div>
</template>

<script>
// import { mapGetters, mapState, mapActions } from 'vuex'
// import studentApi from '@/api/student'
// import classApi from '@/api/class'
// import axios from 'axios'
// import {form} from "@/utils/request"
export default {
  data () {
    return {
      form: {
        classId: null
      },

      formLoading: false,
      rules: {
         classId: [
          { required: true, message: '请选择班级', trigger: 'change' }
        ]
      }
    }
  },
  created () {
    this.getClass();
  },
  methods: {
    submitForm () {
      let _this = this
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.formLoading = true
          studentApi.csStudent(this.form).then(data => {
            if (data.code === 1) {
              _this.$message.success(data.message)
              _this.delCurrentView(_this).then(() => {
                _this.$router.push('/class/student/list')
              })
            } else {
              _this.$message.error(data.message)
              _this.formLoading = false
            }
          }).catch(e => {
            _this.formLoading = false
          })
        } else {
          return false
        }
      })
    },
    cfileUpload(file){
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.formLoading = true

          let files = file.file
          //console.log(file.file)
          let formObj = new FormData();
          //formObj.append("classId", this.form.classId)
          let classId = this.form.classId
          //console.log(classId);
          formObj.append("uploadExcel", files)

      form("/api/admin/excel/import_excel_for_student/"+this.form.classId,formObj).then(res => {
        //console.log(res);
        if (res.code === 1) {
                  this.$message.success(res.message)
                  this.delCurrentView(this).then(() => {
                  this.$router.push('/class/student/list')
                  })
            }
        else {
                   this.$message({
                    showClose: true,
                    message: "上传失败!请查看页面文件学生添加error.xlsx"
                  });
                  this.$refs.upload.clearFiles()
                  axios({
                  method: "post",
                  url: "/api/admin/excel/import_excel_for_student/"+this.form.classId, // 请求地址
                  data:formObj, // 参数
                  responseType: "blob", // 表明返回服务器返回的数据类型
                  headers: {
                    "Content-Type": "application/json"
                  }
                }).then(res => { // 处理返回的文件流
                  const blob = new Blob([res.data]);
                  const fileName = "学生添加error.xlsx";
                  const elink = document.createElement("a");
                  elink.download = fileName;
                  elink.style.display = "none";
                  elink.href = URL.createObjectURL(blob);
                  document.body.appendChild(elink);
                  elink.click();
                  URL.revokeObjectURL(elink.href); // 释放URL 对象
                  document.body.removeChild(elink);
                })
                this.formLoading = false
			      }
        }).catch(e => {
            this.formLoading = false
          })
        }
        else {
          this.$refs.upload.clearFiles()
          return false
        }
      })
    },
    getClass() {
      this.formLoading = true;
      classApi.getClassPageList({ condition: null, pageIndex: 1, pageSize: 100 })
        .then(res => {
          this.formLoading = false;
          if (res.code == 1) {
            this.classList = res.response.list;
          }
        })
        .catch(res => {
          this.formLoading = false;
        });
    },
        fileUpload(file){
      let files = file.file
      console.log(file.file)
      let formObj = new FormData();
      formObj.append('classId',this.classId,"uploadExcel", files)
      form('/api/admin/excel/import_excel_for_student',formObj).then(res => {

        console.log(res);
      })
    },
    resetForm () {
      this.$refs['form'].resetFields()
    },
    ...mapActions('tagsView', { delCurrentView: 'delCurrentView' }),
        //上传照片方法
    handleRemove(file,uploadFile) {
      console.log(file);
    },
    handlePreview(file) {
      console.log(file);
    },
    //handleExceed(files, fileList) {
      //this.$message.warning(
        //`当前限制选择3个文件，本次选择了${
          //files.length
        //}个文件，共选择了${files.length + fileList.length}个文件`
      //);
    //},
    beforeRemove(file) {
      return this.$confirm(`确定移除?`);
    }
  },

  computed: {
    ...mapGetters('enumItem', [
      'enumFormat'
    ]),
    ...mapState('enumItem', {
      sexEnum: state => state.user.sexEnum,
      roleEnum: state => state.user.roleEnum,
      statusEnum: state => state.user.statusEnum,
      levelEnum: state => state.user.levelEnum
    })
  }
}
</script>
<style lang="scss" scoped>

.pager {
   margin: 62px auto;
}
</style>
